//
//  YAYIHomeViewController.m
//  yayi-医生版
//
//  Created by Veer on 16/4/24.
//  Copyright © 2016年 Veer. All rights reserved.
//

#import "YAYIHomeViewController.h"
#import "YAYINavigationController.h"
#import "YAYIEidtPersonalInfoViewController.h"
#import "YAYILoginViewController.h"
#import "YAYIShowAppointViewController.h"
#import "YAYIPatientComeController.h"
#import "YAYIPerformanceViewController.h"
#import "YAYIInterPayController.h"
#import "YAYICertificationViewController.h"

//#import "YAYIMsgViewController.h"
#import "YAYISystemInfoController.h"
#import "YAYIMessageViewController.h"
#import "YAYIMutiPracticeViewController.h"

#import "YAYIMessageCell.h"
#import "YAYIMessageModel.h"
#import "YAYISchedulingViewController.h"
#import "YAYIUserCommentController.h"

#import "UITabBar+badge.h"
#import "YAYIBadgeButton.h"
#import "YAYIUserinfoModel.h"

#import <AudioToolbox/AudioToolbox.h>

#define margin 20.0 * YAYIScreenScale


@interface YAYIHomeViewController ()

//@property (nonatomic, strong) YWConversationListViewController *msgView;
@property (nonatomic, weak) YAYIBadgeButton *badgeButton;

@property (nonatomic, strong) YAYIMessageModel *msgModel;
//@property (nonatomic, strong) SPKitExample *example;

/** 认证标志(0、未提交，1、待处理，2、已认证，3、认证失败) */
@property (nonatomic, assign) NSInteger myVerifyState;

@property (nonatomic, copy) NSString *avatarUrlStr;
@property (nonatomic, copy) NSString *doctorID;
@property (nonatomic, copy) NSString *doctorName;

@end

@implementation YAYIHomeViewController



- (void)didReceiveMemoryWarning
{
    YAYILog(@"----------didReceiveMemoryWarning-----------");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"雅同";
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 15, 0);
    
    self.myVerifyState = -1;
    
    // 默认开启声音
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    if (![userDefaults valueForKey:YAYIVoiceID]) {
        [userDefaults setBool:YES forKey:YAYIVoiceID];
        [userDefaults setBool:YES forKey:YAYIShockID];
    }

    
    [self setupTopView];
    
    [self getMessageCount];

    // 当登录状态改变刷新页面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginStateChanged:) name:YAYILoginNotifyName object:nil];
    
    YAYILog(@"API:%@", API);
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self getUserInfo];
    [self getNoticeCount];
    [self getTagCount];
}


- (void)setupTopView
{
    
    // 130 + 110 * 3
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, SCREEN_width, 130 * YAYIScreenScale + 10 + 212 * YAYIScreenScale + 10);
    self.tableView.tableHeaderView = headerView;
    
    
    UIImageView *topImgView = [[UIImageView alloc] init];
//    topView.backgroundColor = [UIColor orangeColor];
    topImgView.image = [UIImage imageNamed:@"showImg1"];
    [headerView addSubview:topImgView];
    topImgView.frame = CGRectMake(0, 0, SCREEN_width, 130 * YAYIScreenScale);
    
    
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:bottomView];
    bottomView.frame = CGRectMake(0, 130 * YAYIScreenScale + 10, SCREEN_width, 212 * YAYIScreenScale);
    
    CGFloat btnW = SCREEN_width / 3.0;
    CGFloat btnH = 106 * YAYIScreenScale;
    
//    NSArray *titleArray = @[@"预约查看", @"诊间收费", @"我的业绩", @"患者问诊", @"排班管理", @"点点医生"];
    NSArray *titleArray = @[@"预约查看", @"诊间收费", @"我的业绩", @"最新点评", @"排班管理", @"点点医生"];
    
    for (int i = 0; i < titleArray.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        btn.backgroundColor = [UIColor yellowColor];
        btn.tag = i;
        
        NSString *btnImgName = [NSString stringWithFormat:@"homeIcon%d", i + 1];
        [btn setImage:[UIImage imageNamed:btnImgName] forState:UIControlStateNormal];
        [btn setTitle:titleArray[i] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:16];
        [btn setTitleColor:YAYIColor(130, 131, 133) forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        
        CGFloat btnX = (i % 3) * btnW;
        CGFloat btnY = (i / 3) * btnH;
        
        CGSize titleSize = [titleArray[i] sizeWithFont:btn.titleLabel.font];
        CGSize imgSize = btn.currentImage.size;
        btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        btn.contentMode = UIViewContentModeCenter;
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        btn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
        
        CGFloat btnCenterMargin = 15 * YAYIScreenScale;
        CGFloat imgTopMargin = (btnH - btnCenterMargin - titleSize.height - imgSize.height) * 0.5;
        CGFloat titleTopMargin = btnH - imgTopMargin - titleSize.height;
        
        btn.imageEdgeInsets = UIEdgeInsetsMake(imgTopMargin, titleSize.width * 0.5 , -imgTopMargin, -titleSize.width * 0.5);
        btn.titleEdgeInsets = UIEdgeInsetsMake(titleTopMargin, -imgSize.height * 0.5, -titleTopMargin, imgSize.height * 0.5);
        
        
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        [bottomView addSubview:btn];
        [btn addTarget:self action:@selector(homeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        
        if (i == 3) {
            YAYILog(@"btn frame:%@", NSStringFromCGRect(btn.imageView.frame));
            YAYIBadgeButton *badgeButton = [[YAYIBadgeButton alloc] init];
            badgeButton.badgeValue = @"1000";
//            badgeButton.centerX = CGRectGetMaxX(btn.imageView.frame) + 1;
//            badgeButton.centerY = btn.imageView.y;
            [btn addSubview:badgeButton];
            self.badgeButton = badgeButton;
            NSLog(@"btn.imageView.frame:%@",NSStringFromCGRect(btn.imageView.frame));
            [badgeButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(btn.imageView.mas_right).offset(2);
                make.centerY.mas_equalTo(btn.imageView.mas_top).offset(2);
            }];
        }
    }
    
    
    // 线
    UIView *vLineView1 = [[UIView alloc] init];
    vLineView1.backgroundColor = YAYILineColor;
    [bottomView addSubview:vLineView1];
    [vLineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(0);
        make.centerX.mas_equalTo(bottomView.mas_left).offset(btnW);
        make.width.mas_equalTo(1);
        make.bottom.mas_equalTo(bottomView);
    }];
    
    UIView *vLineView2 = [[UIView alloc] init];
    vLineView2.backgroundColor = YAYILineColor;//YAYIColor(235, 236, 237);
    [bottomView addSubview:vLineView2];
    [vLineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(0);
        make.centerX.mas_equalTo(bottomView.mas_left).offset(2 * btnW);
        make.width.mas_equalTo(1);
        make.bottom.mas_equalTo(bottomView);
    }];
    
    UIView *hLineView = [[UIView alloc] init];
    hLineView.backgroundColor = YAYILineColor;
    [bottomView addSubview:hLineView];
    [hLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(bottomView);
        make.centerY.mas_equalTo(bottomView);
        make.height.mas_equalTo(1);
    }];
    
    // 底部线
    UIView *bottomLineView = [[UIView alloc] init];
    bottomLineView.backgroundColor = YAYILineColor;
    [bottomView addSubview:bottomLineView];
    [bottomLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(1.0);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_width);
        make.bottom.mas_equalTo(bottomView);
    }];
}


- (void)loginStateChanged:(NSNotification *)notify
{

    // 刷新表格
    self.myVerifyState = [[NSUserDefaults standardUserDefaults] integerForKey:YAYIVerifyState];
    YAYIUserinfoModel *userInfoModel = notify.object;
    if (userInfoModel) {
        self.avatarUrlStr = [NSString stringWithFormat:@"%@%@", API, userInfoModel.avatar];
        self.doctorID = [NSString stringWithFormat:@"%zd", userInfoModel.id];
        self.doctorName = userInfoModel.fullname;
        self.myVerifyState = userInfoModel.v;
    }
}


#pragma mark - 获取数据
- (void)getUserInfo
{
    // 显示菊花
    //    [SVProgressHUD show];
    if (self.myVerifyState == 2 || self.myVerifyState == 0 || self.myVerifyState == 4) {
        return;
    }
    
    [YAYINetWorking getWithURL:me_personalinfo param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            
            YAYILog(@"getUserInfo返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                
                self.myVerifyState = 0;
            }else{
                // 认证标志(0、未提交，1、待处理，2、已认证，3、认证失败)
                self.myVerifyState = [dict[@"data"][@"v"] integerValue];
                self.avatarUrlStr = [NSString stringWithFormat:@"%@%@", API, dict[@"data"][@"avatar"]];
                self.doctorID = [NSString stringWithFormat:@"%@", dict[@"data"][@"id"]];
                self.doctorName = [NSString stringWithFormat:@"%@", dict[@"data"][@"fullname"]];
            }
        }
        
        [SVProgressHUD dismiss];
    }];
    
}


- (void)getNoticeCount
{
    
    if (self.msgModel) {
        self.msgModel.content = nil;
    }
    [YAYINetWorking getWithURL:noticeCount_url param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                
                 [self.tableView reloadData];
                return;
            }else{
                
                NSArray *dictArray = dict[@"data"];
                NSInteger msgCount = 0;
                NSDictionary *newMsgDict = nil;
                
                for (NSDictionary *dictItem in dictArray) {
                    
                    if ([dictItem[@"updatetime"] integerValue] > [newMsgDict[@"updatetime"] integerValue]) {
                        
                        newMsgDict = dictItem;
                        
                    }
                    msgCount += [dictItem[@"news_count"] integerValue];
                }
                
                YAYIMessageModel *model = [[YAYIMessageModel alloc] init];
                [model setValuesForKeysWithDictionary:newMsgDict];
                model.news_count = msgCount;
                self.msgModel = model;
                
                [self.tableView reloadData];
            }
        }
        
    }];
}


/**
 *  查询是否有患者报道，控制是否显示小红点
 */
- (void)getTagCount
{
    
    [YAYINetWorking getWithURL:queryMsg_url param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
            }else{
                
                NSArray *dataArray = dict[@"data"];
                
                if (dataArray.count > 0) {
                    
                    NSInteger newPatientMsg = [dataArray[0][@"hasnew"] integerValue];
                    if (newPatientMsg > 0) {
                        [self.tabBarController.tabBar showBadgeOnItemIndex:1];
                    }else{
                        [self.tabBarController.tabBar hideBadgeOnItemIndex:1];
                    }
                }
            }
        }else{
            
            YAYILog(@"erro:%@", error);
        }
    }];
    
}


/**
 *  获取消息数量
 */
- (void)getMessageCount
{
    
    NSInteger aCount = 0;//[SPKitExample sharedInstance].ywIMKit.getTotalUnreadCount;
    YAYILog(@"未读消息数量:%ld", aCount);
    self.badgeButton.badgeValue = [NSString stringWithFormat:@"%ld", aCount];
//    self.badgeButton.badgeValue = @"4";
    [UIApplication sharedApplication].applicationIconBadgeNumber = aCount;
    
    if (aCount > 0) {
        [self.tabBarController.tabBar showBadgeOnItemIndex:0];
    }else{
        [self.tabBarController.tabBar hideBadgeOnItemIndex:0];
    }
    
    __block typeof(self) weakself = self;
    
    
//    __weak __typeof(self) weakSelf = self;
    
//    [[[SPKitExample sharedInstance].ywIMKit.IMCore getLoginService] addConnectionStatusChangedBlock:^(YWIMConnectionStatus aStatus, NSError *aError) {
//        
//        [weakSelf setLastConnectionStatus:aStatus];
//        
//        if (aStatus == YWIMConnectionStatusForceLogout || aStatus == YWIMConnectionStatusMannualLogout || aStatus == YWIMConnectionStatusAutoConnectFailed) {
//            /// 手动登出、被踢、自动连接失败，都退出到登录页面
//            if (aStatus != YWIMConnectionStatusMannualLogout) {
//                //                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你的账号已经在其他地方登录，你需要重新登录" delegate:weakSelf cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//                //                [alert show];
//                
//            }
//            
//        }
//        else if (aStatus == YWIMConnectionStatusConnected) {
//            /// 监听群系统消息
//            //[self exampleListenTribeSystemMessagesUpdate];
//            //            [self createSystemInfo];
//            
//            
//        }
//    } forKey:[self description] ofPriority:YWBlockPriorityDeveloper];
    
    /**  方式2 */
//    YWIMKit *ywIMKit = [[YWAPI sharedInstance] fetchIMKitForOpenIM];
//    // 未读消息数
//    NSInteger aCount = ywIMKit.IMCore.getConversationService.countOfUnreadMessages;
//    YAYILog(@"总未读消息数:%ld", aCount);
//    if (aCount > 0) {
//        [self.tabBarController.tabBar showBadgeOnItemIndex:0];
//    }else{
//        [self.tabBarController.tabBar hideBadgeOnItemIndex:0];
//    }
//    
//    __block typeof(self) weakself = self;
//    [ywIMKit.IMCore.getConversationService addConversationTotalUnreadChangedBlock:^(NSUInteger aCount) {
//        
//        YAYILog(@"消息数改变:%ld", aCount);
//        if (aCount > 0) {
//            [weakself.tabBarController.tabBar showBadgeOnItemIndex:0];
//        }else{
//            [weakself.tabBarController.tabBar hideBadgeOnItemIndex:0];
//        }
//    
//    } forKey:@"key" ofPriority:YWBlockPriorityOtherModule];
}


#pragma mark - 点击事件
- (void)homeBtnAction:(UIButton *)sender
{
    
    UIViewController *vc = nil;
    if (0 == sender.tag) { // 预约查看
        
        YAYIShowAppointViewController *appotinVc = [[YAYIShowAppointViewController alloc] init];
        vc = appotinVc;
//        [self.navigationController pushViewController:appotinVc animated:YES];
    }else if (1 == sender.tag){ // 诊间收费
        
        YAYIInterPayController *pay = [YAYIInterPayController new];
        vc = pay;
//        [self.navigationController pushViewController:pay animated:YES];
    }else if (2 == sender.tag){ // 我的业绩
        
        YAYIPerformanceViewController *performanceVc = [[YAYIPerformanceViewController alloc] init];
        [performanceVc.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"clear_bg"] forBarMetrics:UIBarMetricsDefault];
        vc = performanceVc;
//        [self.navigationController pushViewController:performanceVc animated:YES];
    }else if (3 == sender.tag){ // 患者问诊
        
//        [SVProgressHUD showImage:nil status:@"建设中..."];
//        return;
        
        YAYIUserCommentController *commentVc = [[YAYIUserCommentController alloc] init];
        vc = commentVc;
//        [self.navigationController pushViewController:self.msgView animated:YES];
    }else if (4 == sender.tag){ // 排班管理
        
        YAYISchedulingViewController *scheduling = [YAYISchedulingViewController new];
        scheduling.avatarUrlStr = [self.avatarUrlStr copy];
        scheduling.doctorID = [self.doctorID copy];
        scheduling.doctorName = [self.doctorName copy];
        vc = scheduling;
//        [self.navigationController pushViewController:scheduling animated:YES];
    }else if (5 == sender.tag){ // 多点执业
        
        YAYIMutiPracticeViewController *mutiPracticeVc = [[YAYIMutiPracticeViewController alloc] init];
        vc = mutiPracticeVc;
//        [self.navigationController pushViewController:mutiPracticeVc animated:YES];
    }
    
    
    // 判断是否登陆过
    NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
    NSString *cookieName = [userdef valueForKey:YAYILoginCookieKey];
    
    __block typeof(self) weakself = self;
    if (!cookieName) {
        YAYILoginViewController *loginView = [YAYILoginViewController new];
        //        loginView.userInfoModel = self.userInfoModel;
        loginView.loginSuccessOperation = ^(){
            YAYILog(@"登陆成功");
            
            if (weakself.myVerifyState == 0) { // 未提交
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"您还未提交认证，现在去提交？" delegate:weakself cancelButtonTitle:@"取消" otherButtonTitles:@"去提交", nil];
                [alertView show];
                return;
            }else if (weakself.myVerifyState == 1) { // 待处理
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"您认证信息正在审核中，请耐心等待" delegate:weakself cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
                return;
            }else if (weakself.myVerifyState == 3) { // 认证失败
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"您的认证失败，是否重新提交？" delegate:weakself cancelButtonTitle:@"取消" otherButtonTitles:@"去提交", nil];
                [alertView show];
                return;
            }else if (self.myVerifyState == 2){
                
                YAYISchedulingViewController *schededulingVc = (YAYISchedulingViewController *)vc;
                schededulingVc.avatarUrlStr = weakself.avatarUrlStr;
                schededulingVc.doctorID = weakself.doctorID;
                schededulingVc.doctorName = weakself.doctorName;
                [weakself.navigationController pushViewController:schededulingVc animated:YES];
            }
        };
        
        loginView.cancelOperation = ^(){
            YAYILog(@"取消登陆");
//            [weakself.tabBarController setSelectedIndex:0];
        };
        
        YAYINavigationController *nav = [[YAYINavigationController alloc] initWithRootViewController:loginView];
        [self presentViewController:nav animated:YES completion:nil];
    }else{
        
        if (3 == sender.tag) {
            
            
            
            [self.navigationController pushViewController:vc animated:YES];
        }else if (5 == sender.tag) {
        
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            
            if (self.myVerifyState == 0) { // 未提交
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"您还未提交认证，现在去提交？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去提交", nil];
                [alertView show];
                return;
            }else if (self.myVerifyState == 1) { // 待处理
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"您认证信息正在审核中，请耐心等待" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
                return;
            }else if (self.myVerifyState == 3) { // 认证失败
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"您的认证失败，是否重新提交？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去提交", nil];
                [alertView show];
                return;
            }else if (self.myVerifyState == 2){
            
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    }
    
}







#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YAYIMessageCell *cell = [YAYIMessageCell cellWith:tableView];
    if (0 == indexPath.row) {
        cell.lineType = LineTypeTopAndBottom;
    }else{
        cell.lineType = LineTypeBottom;
    }
    cell.model = self.msgModel;
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    YAYIMessageViewController *msgVc = [[YAYIMessageViewController alloc] init];
    
    NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
    NSString *cookieName = [userdef valueForKey:YAYILoginCookieKey];
    
    __block typeof(self) weakself = self;
    if (!cookieName) {
        YAYILoginViewController *loginView = [YAYILoginViewController new];
        //        loginView.userInfoModel = self.userInfoModel;
        loginView.loginSuccessOperation = ^(){
            YAYILog(@"登陆成功");
            
            [weakself.navigationController pushViewController:msgVc animated:YES];
        };
        
        loginView.cancelOperation = ^(){
            YAYILog(@"取消登陆");
            //            [weakself.tabBarController setSelectedIndex:0];
        };
        
        YAYINavigationController *nav = [[YAYINavigationController alloc] initWithRootViewController:loginView];
        [self presentViewController:nav animated:YES completion:nil];
    }else{
    
        [self.navigationController pushViewController:msgVc animated:YES];
    }
    
}


#pragma mark UIAlertView
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if (buttonIndex == 1) {
        
        YAYICertificationViewController *certifyVc = [[YAYICertificationViewController alloc] init];
        __block typeof(self) weakself = self;
        certifyVc.backOperation = ^(){
            weakself.myVerifyState = -1;
            [weakself getUserInfo];
        };
        [self.navigationController pushViewController:certifyVc animated:YES];
    }
}


@end
